package com.yxy.chatserver.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器
 * 用于处理WebSocket连接建立前的握手过程，进行用户认证和参数传递
 */
@Component
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 在握手之前执行的方法
     *
     * @param request    服务器HTTP请求
     * @param response   服务器HTTP响应
     * @param wsHandler  WebSocket处理器
     * @param attributes 会话属性
     * @return true表示继续握手，false表示中断握手
     * @throws Exception 异常信息
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // CORS配置已在WebSocketConfiguration中统一处理
        System.out.println(1111);
        System.out.println("WebSocket连接请求 - 路径: " + request.getURI());
        // 获取HTTP请求对象
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();

            // 从请求参数中获取用户ID
            String userId = httpRequest.getParameter("userId");

            // 如果有用户ID，添加到会话属性中
            if (userId != null && !userId.isEmpty()) {
                attributes.put("userId", userId);
            }

            // 这里可以添加更多的认证逻辑，如token验证等

            // 记录连接请求
            String clientIp = request.getRemoteAddress().getAddress().getHostAddress();
            System.out.println("WebSocket连接请求来自IP: " + clientIp + ", 用户ID: " + userId);
        }

        // 返回true表示允许握手继续
        return true;
    }

    /**
     * 在握手之后执行的方法
     *
     * @param request   服务器HTTP请求
     * @param response  服务器HTTP响应
     * @param wsHandler WebSocket处理器
     * @param exception 握手过程中的异常
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        System.out.println(2222);
        // 握手完成后的处理逻辑
        if (exception != null) {
            System.out.println("WebSocket握手异常: " + exception.getMessage());
        }
    }
}